﻿
namespace Module.Test.Api.Controllers
{
    [AllowAnonymous]
    public class CustomController : ModuleController
    {
        private readonly ICustomAppService _service;
        private readonly IConfiguration _configuration;
        public CustomController(ICustomAppService service, INotificationHandler<DomainNotification> notifications
            ,IConfiguration configuration
            ) : base(notifications)
        {
            _service = service;
            _configuration= configuration; 
        }

        [HttpGet]
        public async Task<IList<CustomDto>> GetList1()
        {
            var ip = HttpContext.Connection.LocalIpAddress;
            var port = HttpContext.Connection.LocalPort;
            var list = await _service.GetAll();
            return list;
        }

        [HttpGet]
        public async Task<IApiResult<IList<CustomDto>>> GetList()
        {
            var list = await _service.GetAll();
            var result = ApiResult.Succeed(list);
            return result;
        }
        [HttpGet]
        public async Task<IApiResult<CustomDto>> Get(long id)
        {
            var info = await _service.GetById(id);
            var result = ApiResult.Succeed(info);
            return result;
        }

        [HttpPost]
        public async Task<IApiResult> Create([FromQuery]CustomDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await ApiResult.FailedAsync("Error ModelState!");
            }
            var result = await _service.Register(dto);
            if (!result)
            {
                return await ApiResult.FailedAsync(_notifications.HasNotifications() ? _notifications.GetText() : "创建失败");
            }

            return await ApiResult.SucceedAsync("创建成功!");
        }
        [HttpPost]
        public async Task<string> Update([FromQuery] CustomDto dto)
        {
            if (!ModelState.IsValid)
            {
                return "Error ModelState!";
            }
            var result = await _service.Update(dto);

            return result.ToString();
        }

        [HttpPost]
        public async Task<string> Remove(long id)
        {
            var result = await _service.Remove(id);

            return result.ToString();
        }


        [HttpPost]
        public async Task<string> ErrorTest()
        {
            throw new MicroException("错误ErrorTest");
        }


        [HttpGet]
        public async Task<string> GetConfiguration(string key)
        {
            if (key.NotNull())
            {
                string str = _configuration[key];
                return str;
            }
            return string.Empty;
        }
    }
}
